<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
    <style>
      * {
        margin: 0;
        padding: 0;
      }

      .content {
        width: 100%;
        height: 2000%;
      }

      .content > div {
        float: left;
        border: 1px solid black;
        padding: 10px;
      }

      .content > div > img {
        width: 300px;
      }
    </style>
  </head>

  <body>
    <div class="content">
      <div>
        <img src="./img/1.png" alt="" />
      </div>

      <div>
        <img src="./img/2.png" alt="" />
      </div>

      <div>
        <img src="./img/3.png" alt="" />
      </div>

      <div>
        <img src="./img/4.png" alt="" />
      </div>

      <div>
        <img src="./img/5.png" alt="" />
      </div>

      <div>
        <img src="./img/6.png" alt="" />
      </div>

      <div>
        <img src="./img/1.png" alt="" />
      </div>

      <div>
        <img src="./img/3.png" alt="" />
      </div>

      <div>
        <img src="./img/5.png" alt="" />
      </div>
    </div>
  </body>

  <script>
    window.onload = function () {
      //获取主容器的宽度
      let content = document.getElementsByClassName('content')[0];
      let contentWidth = content.offsetWidth;
      //获取单个图片单个宽度
      let imgs = content.children;
      let imgsSingle = imgs[0].offsetWidth;
      //计算一行可以排列多少张图片
      let nums = Math.floor(contentWidth / imgsSingle);

      // 收集第一排所有的高度
      let arrHeight = [];
      for (let i = 0; i < imgs.length; i++) {
        if (i < 5) {
          arrHeight.push(imgs[i].offsetHeight);
        } else {
          //创建一个元素
          let obj = {
            minH: arrHeight[0],
            minI: 0,
          };

          for (let j = 0; j < arrHeight.length; j++) {
            if (arrHeight[j] < obj.minH) {
              obj.minH = arrHeight[j];
              obj.minI = j;
            }
          }
          imgs[i].style.position = 'absolute';
          imgs[i].style.left = imgs[obj.minI].offsetLeft + 'px';
          imgs[i].style.top = obj.minH + 'px';
          arrHeight[obj.minI] = arrHeight[obj.minI] + imgs[i].offsetHeight;
        }
      }
    };
  </script>
</html>
